import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import storage from './utils/storage'
import { Notification } from 'element-ui'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login']
let hasRoles = true
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)


  const hasToken = storage.getStorage('dd_admin_user')

  if (hasToken) {
    if (to.path === '/login') {
      next()
      NProgress.done()
    } else {
      if (hasRoles) {
        const accessRoutes = await store.dispatch('permission/generateRoutes', ["admin"])
        // // console.log(accessRoutes,'添加路由')
        // router.addRoutes(accessRoutes)
        hasRoles = false
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      Notification({
        title: '提示',
        message: '请登录后进入系统',
        type: 'error'
      })
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
